#-*-coding:utf-8-*-
# 时间:2019/8/29
# 作者:zfh
import requests
import readConfig
from Log import MyLog


localReadConfig = readConfig.ReadConfig()


class InterfaceWay:

    def __init__(self):
        # 读取配置文件，获取地址以及端口
        global baseUrl, port, timeout, token
        baseUrl = localReadConfig.get_http('baseUrl')
        port = localReadConfig.get_http('port')
        timeout = localReadConfig.get_http('timeout')
        token = localReadConfig.get_cookies('token')
        # self.headers = {}
        self.headers = {"Authorization": "%s" % token }
        self.data = {}
        self.params = {}
        self.url = {}
        self.log = MyLog.get_log()
        self.logger = self.log.logger

    def set_url(self, url):
        self.url = baseUrl + url

    def set_headers(self, header):
        if header != None:
            self.headers = eval(header)

    def set_params(self, param):
        if param != None:
            self.params = eval(param)

    def set_data(self, data):
        self.data = data

    # 定义get方法
    def get(self):
        try:
            response = requests.get(url=self.url, headers=self.headers, data=self.data,params=self.params)
            if response.json()['result']:
                self.logger.info(self.url)
                self.logger.info(response.status_code)
                self.logger.info("----------------接口返回结果为正确----------------")
            return response
        except TimeoutError:
            self.logger.error("超时退出")
            return None
        except:
            self.logger.info(self.url)
            self.logger.info(response.status_code)
            self.logger.error('**********接口返回错误**********')
            return None

    # 定义post方法
    def post(self):
        try:
            response = requests.post(url=self.url, headers=self.headers, params=self.params, data=self.data)
            if response.json()['result']:
                self.logger.info(self.url)
                self.logger.info(response.status_code)
                self.logger.info("----------------接口返回结果为正确----------------")
            # 返回响应结果
            return response
        except TimeoutError:
            self.logger.error("超时退出")
            return None
        except:
            self.logger.info(self.url)
            self.logger.info(response.status_code)
            self.logger.error('**********接口返回错误**********')
            return None


# t = InterfaceWay()
# t.set_url('')
# print(t.get())